<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- card区域 -->
    <el-card>
      <!-- 提示行 -->
      <el-row>
        <el-alert title="注意：只允许为第三方分类设置相关参数！" type="warning" show-icon :closable="false"></el-alert>
      </el-row>
      <!-- 选择商品分类 -->
      <el-row>
        选择商品分类：
        <el-cascader
          v-model="checkedKeys"
          :options="goodsCateList"
          :props="goodsCateProps"
          @change="CateChanged()"
          clearable
        ></el-cascader>
      </el-row>
      <!-- 标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加动态参数按钮 -->
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            @click="addParamsDialogVisible=true"
          >添加参数</el-button>
          <!-- 参数表单 -->
          <el-table :data="manyParamsList" border stripe>
            <!-- 展开 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- {{scope.row.attr_vals}} -->
                <el-tag
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="closeTag(i,scope.row)"
                >{{item}}</el-tag>
                <!-- 添加 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <!-- 参数名称 -->
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <!-- 操作 -->
            <el-table-column label="操作">
              <!-- 作用域插槽 -->
              <template slot-scope="scope">
                <!-- {{scope.row}} -->
                <!-- 修改按钮 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editParamsData(scope.row)"
                >编辑</el-button>
                <!-- 删除按钮 -->

                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="delManyParams(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 按钮 -->
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            @click="addParamsDialogVisible=true"
          >添加属性</el-button>
          <!-- 表单 -->
          <el-table :data="onlyParamsList" border stripe>
            <!-- 展开 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- {{scope.row.attr_vals}} -->
                <el-tag
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="closeTag(i,scope.row)"
                >{{item}}</el-tag>
                <!-- 添加 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <!-- 参数名称 -->
            <el-table-column prop="attr_name" label="静态属性"></el-table-column>
            <!-- 操作 -->
            <el-table-column label="操作">
              <!-- 作用域插槽 -->
              <template slot-scope="scope">
                <!-- {{scope.row}} -->
                <!-- 修改按钮 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editParamsData(scope.row)"
                >编辑</el-button>
                <!-- 删除按钮 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteProps(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog :title="'添加'+DialogText" :visible.sync="addParamsDialogVisible" width="50%">
      <!-- 表单 -->
      <el-form
        ref="addParamsformRef"
        :model="addParamsform"
        label-width="80px"
        :rules="addParamsformRules"
      >
        <el-form-item :label="DialogText" prop="attr_name">
          <el-input v-model="addParamsform.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetParamsForm()">取 消</el-button>
        <el-button type="primary" @click="addParams()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数对话框 -->
    <el-dialog :title="'修改'+DialogText" :visible.sync="editParamsDialogVisible" width="50%">
      <!-- 表单 -->
      <el-form
        ref="editParamsformRef"
        :model="editParamsForm"
        label-width="80px"
        :rules="editParamsformRules"
      >
        <el-form-item :label="DialogText" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetParamsForm2()">取 消</el-button>
        <el-button type="primary" @click="editParams()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 编辑参数对话框显示
      editParamsDialogVisible: false,
      // 编辑参数表单
      editParamsForm: {
        id: "",
        attrId: "",
        attr_name: "",
      },
      //   编辑表单参数验证规则
      editParamsformRules: {
        attr_name: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
      },
      // 添加参数表单
      addParamsform: {
        attr_name: "",
      },
      // 添加参数对话框
      addParamsDialogVisible: false,
      // 动态参数
      manyParamsList: [],
      //   静态参数
      onlyParamsList: [],
      // 商品分类列表
      goodsCateList: [],
      //   级联选择器配置选项
      goodsCateProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      //   级联选择器选中id的数组
      checkedKeys: [],
      //   标签页
      activeName: "many",
      //   添加参数表单验证规则
      addParamsformRules: {
        attr_name: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getGoodsCate();
  },
  methods: {
    //   关闭标签删除参数
    closeTag(i, val) {
      // 删除索引开始的1个参数，并修改原数组
      val.attr_vals.splice(i, 1);
      this.saveAttrVals(val);
    },
    // saveAttrVals
    async saveAttrVals(val) {
      //   发起网络请求
      const { data: res } = await this.$http.put(
        "categories/" + val.cat_id + "/attributes/" + val.attr_id,
        {
          attr_name: val.attr_name,
          attr_sel: val.attr_sel,
          attr_vals: val.attr_vals.join(" "),
        }
      );
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg);
      }
      this.$message.success("修改成功！");
    },
    //   按钮输入框的切换
    showInput(val) {
      val.inputVisible = true;
      //   自动获取焦点
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // handleInputConfirm
    handleInputConfirm(val) {
      if (val.inputValue.trim().length === 0) {
        val.inputValue = "";
        val.inputVisible = false;
        return;
      }
      val.attr_vals.push(val.inputValue);
      this.saveAttrVals(val);
      val.inputVisible = false;
      val.inputValue = "";
    },

    //   编辑参数对话框
    editParamsData(param) {
      this.editParamsForm.id = param.cat_id;
      this.editParamsForm.attrId = param.attr_id;
      this.editParamsForm.attr_name = param.attr_name;
      this.editParamsDialogVisible = true;
    },
    // 编辑提交参数
    editParams() {
      this.$refs.editParamsformRef.validate(async (valid) => {
        if (!valid) return;
        // 编辑提交参数
        const { data: res } = await this.$http.put(
          `categories/${this.editParamsForm.id}/attributes/${this.editParamsForm.attrId}
            `,
          {
            attr_name: this.editParamsForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (res.meta.status !== 200) {
          this.$message.error(res.meta.msg);
        }
        this.editParamsDialogVisible = false;
        this.editParamsForm.id = "";
        this.editParamsForm.attrId = "";
        this.getParamsList();
      });
    },
    //   重置编辑参数表单
    resetParamsForm2() {
      this.$refs.editParamsformRef.resetFields();
      this.editParamsDialogVisible = false;
    },

    //   删除静态属性
    async deleteProps(param) {
      // 发起网络请求删除静态属性
      const { data: res } = await this.$http.delete(
        "categories/" + param.cat_id + "/attributes/" + param.attr_id
      );
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg);
      } else {
        this.$message.success("删除成功！");
        // 重新获取参数信息
        this.getParamsList();
      }
    },
    //   重置添加参数表单
    resetParamsForm() {
      this.$refs.addParamsformRef.resetFields();
      this.addParamsDialogVisible = false;
    },
    //   添加参数
    addParams() {
      // 预校验
      this.$refs.addParamsformRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          `categories/${this.thirdId}/attributes`,
          {
            attr_name: this.addParamsform.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (res.meta.status !== 201) {
          this.$message.error(res.meta.msg);
        } else {
          // 成功
          this.getParamsList();
          this.addParamsDialogVisible = false;
          this.addParamsform.attr_name = "";
        }
      });
    },
    //   删除动态参数
    async delManyParams(param) {
      // 发起网络请求删除动态参数
      const { data: res } = await this.$http.delete(
        "categories/" + param.cat_id + "/attributes/" + param.attr_id
      );
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg);
      } else {
        this.$message.success("删除成功！");
        // 重新获取参数信息
        this.getParamsList();
      }
    },
    //   获得商品分类数据
    async getGoodsCate() {
      //发起网络请求 获取商品分类数据
      const { data: res } = await this.$http.get("categories");
      this.goodsCateList = res.data;
      console.log(this.goodsCateList);
    },
    //   标签页变化
    handleClick() {
      console.log(this.activeName);
      if (this.checkedKeys.length === 3) {
        this.getParamsList();
      } else {
        this.$message.error("请选择分类的商品！");
      }
    },
    //   级联选择器change事件
    CateChanged() {
      console.log("here");
      console.log(this.checkedKeys);
      if (this.checkedKeys.length !== 3) {
        this.manyParamsList = [];
        this.onlyParamsList = [];
        this.getParamsList();
      } else {
        this.getParamsList();
      }
    },

    // 获取参数列表
    async getParamsList() {
      // 发起网络请求获取参数列表
      const { data: res } = await this.$http.get(
        `categories/${this.thirdId}/attributes`,
        {
          params: {
            sel: this.activeName,
          },
        }
      );
      if (res.meta.status !== 200) {
        return;
      } else {
        //把attr_vals从字符串变成数组
        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];

          //   为每一个item项添加inputVisible和inputValue
          item.inputVisible = false;
          item.inputValue = "";
        });
        console.log("attr-vals");
        console.log(res.data);

        if (this.activeName === "many") {
          this.manyParamsList = res.data;
          console.log("manyParamsList");
          console.log(this.manyParamsList);
        }
        if (this.activeName === "only") {
          this.onlyParamsList = res.data;
          console.log("onlyParamsList");
          console.log(this.onlyParamsList);
        }
      }
    },
  },

  computed: {
    //   计算添加参数对话框是动态还是静态文本
    DialogText() {
      if (this.activeName === "many") {
        return "动态参数";
      }
      return "静态属性";
    },
    //   选中的第三级分类的ID
    thirdId() {
      if (this.checkedKeys.length === 3) {
        return this.checkedKeys[2];
      } else {
        return null;
      }
    },
    // 设置按钮是否禁用
    isBtnDisabled() {
      if (this.checkedKeys.length === 3) {
        return false;
      }
      return true;
    },
  },
};
</script>
<style lang="less" scoped>
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>